package models

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"os"
)

var (
	db *gorm.DB
)

func init() {
	var err error
	if err = os.MkdirAll("data", 07777); err != nil {
		panic("failed " + err.Error())
	}
	db, err = gorm.Open("sqlite3", "data/data.db")
	if err != nil {
		panic("failed to connect database")
	}

	db.AutoMigrate(&User{}, &Notes{})

	//如果数据库里没有用户表，我们新增一条admin数据
	var count int
	if err := db.Model(&User{}).Count(&count).Error; err == nil && count == 0 {
		db.Create(&User{
			Name:   "admin",
			Phone:  "13618627969",
			Pwd:    "123456",
			Avatar: "/static/img/avatar.png",
			Role:   0, //0代表管理员,1代表正常用户
		})
	}

	//defer db.Close()
}
